package com.creditease.tmsp.modules.sys.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.creditease.tmsp.common.servlet.ValidateCodeServlet;
import com.creditease.tmsp.common.utils.Encodes;
import com.creditease.tmsp.modules.sys.entity.SysResource;
import com.creditease.tmsp.modules.sys.entity.SysUser;
import com.creditease.tmsp.modules.sys.entity.SysUserRole;
import com.creditease.tmsp.modules.sys.service.RoleResourceService;
import com.creditease.tmsp.modules.sys.service.RoleService;
import com.creditease.tmsp.modules.sys.service.SysResourceService;
import com.creditease.tmsp.modules.sys.service.UserRoleService;
import com.creditease.tmsp.modules.sys.service.UserService;
import com.creditease.tmsp.modules.sys.web.LoginController;

/**
 * @Description：系统安全认证实现类
 * @author：
 * @CreateDate：
 * @Company:
 * @version V1.0
 */
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private RoleResourceService roleResourceService;
	@Autowired
	private SysResourceService sysResourceService;
	
	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		
		if (LoginController.isValidateCodeLogin(token.getUsername(), false, false)){
			// 判断验证码
			Session session = SecurityUtils.getSubject().getSession();
			String code = (String)session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
			if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)){
				throw new CaptchaException("验证码错误.");
			}
		}

		SysUser user = userService.getByLoginName(token.getUsername());
		if (user != null) {
			byte[] salt = Encodes.decodeHex(user.getPwd().substring(0,16));
			return new SimpleAuthenticationInfo(new Principal(user), 
					user.getPwd().substring(16), ByteSource.Util.bytes(salt), getName());
		} else {
			return null;
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Principal principal = (Principal) getAvailablePrincipal(principals);
		SysUser user = userService.getByLoginName(principal.getLoginName());
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			List<SysResource> resourceList = new ArrayList<SysResource>();
			if(user.isAdmin()){
				resourceList = sysResourceService.findAllMenu();			
			}else{
				Map<String,Object> params = new HashMap<String,Object>();
				params.put("userId", user.getId());
				List<SysUserRole> userRoleLsit = userRoleService.find(params);
				List<String> roleStringLsit = new ArrayList<String>();
				for(SysUserRole sur : userRoleLsit){
					roleStringLsit.add(sur.getRoleId());
				}
				resourceList = sysResourceService.findByRoles(roleStringLsit);			
		    }
			for(SysResource sr:resourceList){
				setPermission(sr, info);
			}	
			// 更新登录IP和时间
			user.setLoginIp(SecurityUtils.getSubject().getSession().getHost());
			user.setLoginTime(new Date());
			userService.update(user);
			return info;
		} else {
			return null;
		}
	}
	
	/**
	 * @Description:通过菜单实体增加权限
	 * @author：
	 * @param sr
	 * @param info
	 */
	private void setPermission(SysResource sr,SimpleAuthorizationInfo info){
		if(StringUtils.isNotBlank(sr.getPermission())){
			// 添加基于Permission的权限信息
			for (String permission : StringUtils.split(sr.getPermission(),",")){
				//去除路径最后的"/"防止通配出错
				if(permission.endsWith("/")&&!permission.equals("/")){
					permission = permission.substring(0,permission.length()-1);
				}
				if(permission.endsWith("form")){
					permission = permission.substring(0,permission.length()-5);
				}
				info.addStringPermission(permission);
			}
		}
		if(StringUtils.isNotBlank(sr.getHref())){
			// 添加基于Permission的权限信息
			String permission = sr.getHref();
			//去除路径最后的"/"防止通配出错
			if(permission.endsWith("/")&&!permission.equals("/")){
				permission = permission.substring(0,permission.length()-1);
			}
			info.addStringPermission(permission);
		}
	}
	
	/**
	 * 设定密码校验的Hash算法与迭代次数
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(userService.HASH_ALGORITHM);
		matcher.setHashIterations(userService.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}
	
	/**
	 * 清空用户关联权限认证，待下次使用时重新加载
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清空所有关联认证
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	
	/**
	 * 授权用户信息
	 */
	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;
		
		private String id;
		private String loginName;
		private String nickName;
		private String name;
		
		public Principal(SysUser user) {
			this.id = user.getId();
			this.loginName = user.getLoginName();
			this.nickName = user.getNickName();
			this.setName(StringUtils.isBlank(user.getNickName())?user.getLoginName():user.getNickName());
		}

		public String getId() {
			return id;
		}

		public String getLoginName() {
			return loginName;
		}

		public String getNickName() {
			return nickName;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}


	}
}
